package cn.eu.common.query.model;

import cn.eu.common.query.annotation.Table;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.TableInfo;

import com.github.yulichang.toolkit.TableHelper;
import lombok.Getter;
import lombok.Setter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
@Setter
public class TableModel {

    private TableInfo table;

    private String alias;

    private String joinField;

    private boolean logicDelete;

    private List<ConditionModel> conditions;

    public TableModel(Table table) {
        Class<?> target = table.target();
        TableInfo tableInfo = TableHelper.get(target);
        if(tableInfo == null) throw new RuntimeException(StrUtil.format("获取实体映射表信息错误[{}]", target.getName()));
        this.table = tableInfo;
        this.alias = StrUtil.toCamelCase(StrUtil.blankToDefault(tableInfo.getTableName(), table.alias()));
        this.logicDelete = table.logicDelete();
        String tableKey = tableInfo.getKeyProperty();
        String thisField = table.thisField();
        if(StrUtil.isBlank(thisField) || StrUtil.equals(tableKey, thisField)) {
            this.joinField = tableInfo.getKeyColumn();
        } else {
            this.joinField = tableInfo.getFieldList().stream().filter(field -> field.getProperty().equals(thisField))
                    .findFirst().orElseThrow(() -> new RuntimeException(StrUtil.format("数据表不存在属性[{}]", thisField)))
                    .getColumn();
        }
        this.conditions = Arrays.stream(table.conditions())
            .map(condition -> new ConditionModel(tableInfo, this.alias, condition))
            .collect(Collectors.toList());
    }

    public Class<?> getTableClass() {
        return table.getEntityType();
    }

    public String getLogicDeleteSql() {
        return logicDelete ? StrUtil.format("{}.{}", this.alias, table.getLogicDeleteSql(false, logicDelete)) : "";
    }

}
